// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// O [author] rhyme_lph
// R [email]  rhymelph@gmail.com
// I [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/balance_choose_button.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_item.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/sales/views/sales_invoice_provider.dart';
import 'package:finance_app/src/provider/dashboard/sales/sales_provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SalesInvoiceView extends StatefulWidget {
  @override
  _SalesInvoiceViewState createState() => _SalesInvoiceViewState();
}

class _SalesInvoiceViewState extends State<SalesInvoiceView>
    with
        StatefulPresenter<SalesInvoiceView, SalesProvider,
            SalesInvoiceProvider>,
        KeepAliveMixin {
  @override
  Widget wrapperBody(Widget body) {
    return listBuilder<bool>(
        selector: (_, __) => __.hasUp,
        builder: (BuildContext context, bool value, Widget child) =>
            SmartRefresher(
              controller: provider.refreshController,
              onRefresh: provider.onRefresh,
              onLoading: provider.onLoadMore,
              enablePullUp: value,
              child: child,
            ),
        child: body);
  }

  @override
  Widget buildWidget(BuildContext context) => ListView(
        controller: provider.controller,
        children: [
          AppSpaces.h20,
          listBuilder<String>(
            selector: (_, __) => __.data?.unpaidInvoice,
            builder: (BuildContext context, String value, Widget child) =>
                BalanceChooseButton(
              title: S.current.unpaid_invoice,
              number: value,
              onTap: provider.onNavUnpaidInvoice,
              numberColor: aceGreenColor28,
              borderColor: aceGreenColor28,
            ),
          ),
          AppSpaces.h10,
          listBuilder<String>(
            selector: (_, __) => __.data?.overdueInvoice,
            builder: (BuildContext context, String value, Widget child) =>
                BalanceChooseButton(
              title: S.current.overdue_invoice,
              number: value,
              onTap: provider.onNavOverdueInvoice,
              numberColor: aceGreenColor28,
              borderColor: aceGreenColor28,
            ),
          ),
          AppSpaces.h10,
          listBuilder<String>(
            selector: (_, __) => __.data?.paidInvoice,
            builder: (BuildContext context, String value, Widget child) =>
                BalanceChooseButton(
              title: S.current.paid_invoice,
              number: value,
              onTap: provider.onNavPaidInvoice,
              numberColor: aceGreenColor28,
              borderColor: aceGreenColor28,
            ),
          ),
          AppSpaces.h20,
          ListHeaderItem(
            title: S.current.all_invoices,
          ),
          _buildFilterWidget(),
          listBuilder<int>(
            selector: (_, __) => __.transactionList?.length,
            builder: (BuildContext context, int value, Widget child) =>
                value == null
                    ? super.buildLoadingWidget(context)
                    : value == 0
                        ? super.buildEmptyWidget(provider, context)
                        : Column(
                            children: _buildTransactionList(),
                          ),
          )
        ],
      );

  Widget _buildFilterWidget() => Container(
        padding: EdgeInsets.only(top: getDp(20)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _buildTimeSelect(),
            PressedOpacityButton(
              onPressed: provider.onNavViewAll,
              padding: EdgeInsets.symmetric(horizontal: getDp(20)),
              child: Text(
                S.current.view_all,
                style: TextStyle(
                  color: aceBlueColor,
                  fontSize: getSp(16),
                  fontWeight: FontWeight.w700,
                  height: 14 / 16,
                ),
              ),
            )
          ],
        ),
      );

  Widget _buildTimeSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectTime,
            ),
        selector: (_, __) => __.currentSelectTime);
  }

  List<Widget> _buildTransactionList() {
    List<Widget> child = [];
    for (final item in provider.transactionMap.entries) {
      child.add(TransactionRecordTitleItem(
        title: item.key,
      ));
      child.addAll(List.generate(
          item.value.length,
          (index) => listBuilder<TransactionEntity>(
                selector: (_, __) => item.value[index],
                builder:
                    (BuildContext context, TransactionEntity e, Widget child) {
                  return TransactionRecordItem(
                    onTap: () => provider.onNavTransactionDetail(e),
                    tag: TransactionTypeUtils.getTransactionType(
                        e.transactionType),
                    name: e.name,
                    currencyCode: e.currencyCode,
                    time: DateTimeUtils.formatDateTimeString(e.issuedAt),
                    amount: e.total?.toDouble(),
                    billNumber: e.number,
                    isUnpaid: e.status == 'open' && e.employeeId == null,
                    status: e.isOverdue == 1 && e.status == 'open'
                        ? 'Overdue'
                        : FormUtils.getStatus(
                            TransactionTypeUtils.getTransactionTypeStatus(
                                e.transactionType),
                            e.status,
                            e.status == 'open' && e.employeeId == null ? 1 : 0),
                  );
                },
              )));
    }
    return child;
  }
}
